import wx
import gui.posnet_p2p_node_gui
import gui.dialog
import posnet_tcp_client


def get_host_port(self):
	try:
		host = self.text_host.GetValue()
		port = int(self.text_port.GetValue())
		return (host,port)
	except Exception,e:
		gui.dialog.show_error(self,'while trying to get host or port\n'+str(e))
	return (None,None)	


def handle_refresh_poset(self,event = None):
	host,port= self.get_host_port()
	if host is not None:	
		try:
			self.Poset = posnet_tcp_client.posnet_ping(  (host,port), 0 )
			self.Poset_keys = self.Poset.keys()
			self.Poset_keys.sort()
			self.text_poset.SetValue("\n".join( [ str(key[-1]) for key in self.Poset_keys ] )  )	
		except Exception,e:
			self.text_poset.SetValue("error while trying to get poset\n"+str(e))


def handle_connect(self,event):
	host,port= self.get_host_port()
	if host is not None:	
		try:
			dat = posnet_tcp_client.posnet_state_request(  (host,port), 0 )
			self.text_state.SetValue("ok: "+str(len(dat))+" nodes")	
			self.handle_refresh_poset()	
		except Exception,e:
			self.text_state.SetValue("error")	
			gui.dialog.show_error(self,'connect: error while trying to get state\n'+str(e))
		
		
	

class overlay_node_app(wx.App):
    def OnInit(self):
        wx.InitAllImageHandlers()
	setattr(gui.posnet_p2p_node_gui.posnet_overlay_node_frame,"handle_connect",handle_connect)
	setattr(gui.posnet_p2p_node_gui.posnet_overlay_node_frame,"handle_refresh_poset",handle_refresh_poset)
	setattr(gui.posnet_p2p_node_gui.posnet_overlay_node_frame,"get_host_port",get_host_port)
        main_frame = gui.posnet_p2p_node_gui.posnet_overlay_node_frame(None, -1, "")
        self.SetTopWindow(main_frame)
	#-------------------------------
	# set attributes to the gui frame
	names =  {  "Poset" : dict(), "Poset_keys":[],"Query":dict(),"Insert":dict(), "Draw":dict()}
	for name,def_val in names.items():
		#obj = getattr(  main_frame  ,name)
		#for y in ("filename","dirname"):
		#	setattr(obj,y,"")
		#setattr(obj,name,def_val)
		setattr(main_frame,name,def_val)
	
        main_frame.Show()
        return 1

# end of class posnet_overlay_node_app

if __name__ == "__main__":
	posnet_overlay_node_gui = overlay_node_app(0)
	posnet_overlay_node_gui.MainLoop()
